package cn.hackcloud.concurrency.future;

/**
 * 实现Future
 * Created by www.ibfbc.com
 */
public class FutureTask<T> implements Future<T> {
    //计算结果
    private T result;
    //任务是否完成
    private boolean isDone = false;
    //定义对象锁
    private final Object LOCK = new Object();

    /**
     * 任务还没完成时，调用get方法将会被阻塞
     * @return T
     * @throws InterruptedException
     */
    @Override
    public T get() throws InterruptedException {
        synchronized (LOCK) {

            while (!isDone) {
                LOCK.wait();
            }
        }
        return result;
    }

    /**
     * 计算完成时为result指定结果
     * 并且将isDone设置为true
     * 同时唤醒阻塞中的线程
     * @param result
     */
    protected void finish(T result) {
        synchronized (LOCK) {
            if (isDone) {
                return;
            }
            this.result = result;
            this.isDone = true;
            LOCK.notifyAll();
        }
    }

    @Override
    public boolean done() {
        return isDone;
    }
}
